package com.yesun.task.pipeline.handler.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yesun.core.util.FileUtils;
import com.yesun.server.mdp.service.client.config.HttpConfig;
import com.yesun.server.mdp.service.client.impl.DefaultClient;
import com.yesun.server.mdp.service.client.impl.http.HttpRequestContext;
import com.yesun.server.mdp.service.client.impl.http.HttpResponseContext;
import com.yesun.server.mdp.service.client.utils.SpiderUtil;
import com.yesun.task.pipeline.common.Constant;
import com.yesun.task.pipeline.common.StockCode;
import com.yesun.task.pipeline.domain.dto.JobDto;
import com.yesun.task.pipeline.domain.dto.TaskDto;
import com.yesun.task.pipeline.handler.Executor;
import com.yesun.task.pipeline.handler.Handler;
import com.yesun.task.pipeline.handler.Loader;
import com.yesun.task.pipeline.worker.ParallelWorker;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

//解禁批次数据
@Slf4j
public class LiftBanHandler extends Handler {

    static DefaultClient client = new DefaultClient();
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyyMMdd");
    static String TODAY = shortSdf.format(Calendar.getInstance().getTime());

    public LiftBanHandler(JobDto jobDto) {
        super(jobDto);
    }

    @Override
    public Loader getLoader() {
        //实例化
        return new Loader() {
            @Override
            public void load(BlockingQueue queue) {
                log.info("加载解禁批次数据采集子任务...");
                //实现资金流入子任务，插入到队列
                String[] arr = StockCode.STOCK_CODE.split(",");
                for(String code : arr) {
                    String url = "https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112307817940946862607_1692532491421&sortColumns=FREE_DATE&sortTypes=-1&pageSize=500&pageNumber=1&reportName=RPT_LIFT_STAGE&filter=(SECURITY_CODE%3D"+ code +")&columns=SECURITY_CODE%2CSECURITY_NAME_ABBR%2CFREE_DATE%2CCURRENT_FREE_SHARES%2CABLE_FREE_SHARES%2CLIFT_MARKET_CAP%2CFREE_RATIO%2CNEW%2CB20_ADJCHRATE%2CA20_ADJCHRATE%2CFREE_SHARES_TYPE%2CTOTAL_RATIO%2CNON_FREE_SHARES%2CBATCH_HOLDER_NUM&source=WEB&client=WEB";
                    TaskDto taskDto = new TaskDto();
                    taskDto.setJobName(jobDto.getJobName());
                    taskDto.setName(code + " 解禁批次数据采集任务");
                    taskDto.setTag(Constant.JOB_TAG_LIFT_BAN);

                    Map<String,String> map = new HashMap<>();
                    map.put("url", url);
                    map.put("code", code);
                    map.put("saveTo", "/df_lift_ban/"+ shortSdf.format(new Date()) +"/"+code+".csv");//暂时只支持保存到磁盘
                    taskDto.setMap(map);
                    queue.offer(taskDto);

                    //加入MAP_TASK
                    ParallelWorker.MAP_TASK.put(taskDto.getName(), taskDto.getJobName());

                    log.info("添加子任务：" + taskDto.getName());
                }
            }
        };
    }

    @Override
    public Executor getExecutor() {
        return new Executor() {
            @Override
            public void execute(TaskDto taskDto) {
                //执行task的采集
                log.info("execute：" + taskDto.getName());
                HttpConfig config = new HttpConfig(taskDto.getMap().get("url"), HttpConfig.HTTP_METHOD_GET);
                config.setEnctype("");
                config.setEncoding("UTF-8");
                HttpRequestContext request = new HttpRequestContext(config);
                try {
                    HttpResponseContext response = (HttpResponseContext) client.execute(request);
                    String content = response.getContentAsString("UTF-8");
                    content = content.substring(content.indexOf("{"), content.lastIndexOf("}")+1);
                    log.debug("content:"+content);
                    /**
                     {"SECURITY_CODE":"300065",
                     "SECURITY_NAME_ABBR":"海兰信",
                     "FREE_DATE":"2023-06-26 00:00:00",
                     "CURRENT_FREE_SHARES":3058.1039,
                     "ABLE_FREE_SHARES":3058.1039,
                     "LIFT_MARKET_CAP":36360.855371,
                     "FREE_RATIO":0.04646562693,
                     "NEW":11.89,
                     "B20_ADJCHRATE":-1.12269447,
                     "A20_ADJCHRATE":-6.89375507,
                     "FREE_SHARES_TYPE":"定向增发机构配售股份",
                     "TOTAL_RATIO":0.042211005828,
                     "NON_FREE_SHARES":6633.6969,
                     "BATCH_HOLDER_NUM":11},
                    **/
                    StringBuffer sb = new StringBuffer("采集日期,股票代码,股票名称,解禁时间,解禁数量,实际解禁数量,实际解禁市值,占流通股比例,解禁时股价,解禁后20日股价涨幅,解禁前20日股价涨幅,解禁类型,占总市值比例,未解禁数量,解禁股东数量\n"); //股价最好从其他表获取
                    JSONArray jsonArray = JSONObject.parseObject(content)
                            .getJSONObject("result")
                            .getJSONArray("data");
                    jsonArray.stream()
                            .forEach(line -> {
                                JSONObject obj = (JSONObject)line;
                                sb.append(TODAY + "," + obj.get("SECURITY_CODE") + ","
                                        + obj.get("SECURITY_NAME_ABBR") + ","
                                        + obj.get("FREE_DATE") + ","
                                        + obj.get("CURRENT_FREE_SHARES") + ","
                                        + obj.get("ABLE_FREE_SHARES") + ","
                                        + obj.get("LIFT_MARKET_CAP") + ","
                                        + obj.get("FREE_RATIO") + ","
                                        + obj.get("NEW") + ","
                                        + obj.get("A20_ADJCHRATE") + ","
                                        + obj.get("B20_ADJCHRATE") + ","
                                        + obj.get("FREE_SHARES_TYPE").toString().replace(",","|") + ","
                                        + obj.get("TOTAL_RATIO") + ","
                                        + obj.get("NON_FREE_SHARES") + ","
                                        + obj.get("BATCH_HOLDER_NUM") + ",\n");
                            });

                    //log.info(sbResult.toString());
                    //save to
                    FileUtils.saveCsv(Constant.BASE_PATH + taskDto.getMap().get("saveTo"), sb.toString(), "UTF-8");
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
